/**
 * Copyright (c) 2011-2013, dafei 李飞 (myaniu AT gmail DOT com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fas.core.plugin.shiro.core;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;

import com.fas.core.BaseController;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;

public class ShiroInterceptor implements Interceptor {

	public void intercept(Invocation ai) {

		BaseController controller = (BaseController) ai.getController();
		HttpServletRequest request = controller.getRequest();
		String header = request.getHeader("X-Requested-With");
		boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
		
		AuthzHandler ah = ShiroKit.getAuthzHandler(ai.getActionKey());
		// 存在访问控制处理器。
		if (ah != null) {
			try {

				// 登录前访问页面缓存
				if (!SubjectKit.isAuthed()) {
					WebUtils.saveRequest(ai.getController().getRequest());
				}

				// rememberMe自动登录
				Subject subject = SubjectKit.getSubject();
				if (!subject.isAuthenticated() && subject.isRemembered()) {
					Object principal = subject.getPrincipal();
					if (principal == null) {
						SubjectKit.getSubject().logout();
					}
				}

				// 执行权限检查。
				ah.assertAuthorized();
			} catch (UnauthenticatedException lae) {
				// RequiresGuest，RequiresAuthentication，RequiresUser，未满足时，抛出未经授权的异常。
				// 如果没有进行身份验证，返回HTTP401状态码,或者跳转到默认登录页面
				if(isAjax){
					controller.returnJsonResult(false, "Unauthenticated",null);
				}else{
					if (StrKit.notBlank(ShiroKit.getLoginUrl())) {
						// 保存登录前的页面信息,只保存GET请求。其他请求不处理。
						if (ai.getController().getRequest().getMethod().equalsIgnoreCase("GET")) {
							ai.getController().setSessionAttr(ShiroKit.getSavedRequestKey(),ai.getActionKey());
						}
						ai.getController().redirect(ShiroKit.getLoginUrl());
					} else {
						ai.getController().renderError(401);
					}
				}
				return;
			} catch (AuthorizationException ae) {
				// RequiresRoles，RequiresPermissions授权异常
				if(isAjax){
					controller.returnJsonResult(false,"没有该操作权限!",null);
				}else{
					// 如果没有权限访问对应的资源，返回HTTP状态码403，或者调转到为授权页面
					if (StrKit.notBlank(ShiroKit.getUnauthorizedUrl())) {
						ai.getController().redirect(ShiroKit.getUnauthorizedUrl());
					} else {
						ai.getController().renderError(403);
					}
				}
				return;
			}
		}
		// 执行正常逻辑
		ai.invoke();
	}
}
